package net.mmgg.android.bm;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSON;

public class ConfigUtil {

	public synchronized DataBean getData(Config config) {
		String str = CustomerHttpClient.get(config.getUrl() + "?id=" + config.getCode());
		if (null == str) {
			return null;
		}
		ConfigBean configBean = JSON.parseObject(str, ConfigBean.class);
		DataBean dataBean = new DataBean();
		dataBean.setKeyword(Arrays.asList(configBean.getOct_kw()));
		dataBean.setUrl(Arrays.asList(configBean.getOct_url()));
		return dataBean;
	}

	public synchronized void request(String action, Map<String, String> param, DataBean dataBean, Handler handler) {

		List<String> keywords = dataBean.getKeyword();
		List<String> urls = dataBean.getUrl();
		Map<String, String> hrefs = new HashMap<String, String>();
		//log(handler, "从服务器获取到关键词:" + keywords.size() + "个");
		//log(handler, "从服务器获取到URL:" + urls.size() + "个");
		for (String key : keywords) {
			//log(handler, "开始搜索关键字:" + key);
			log(handler,"开始");
			String keyword = "";
			try {
				keyword = URLEncoder.encode(key, "utf-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
				return;
			}
			// 暂停半秒
			try {
				//log(handler, "暂停半秒...");
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			// 时间
			String time = String.valueOf(new Date().getTime());
			time = time.substring(time.length() - 7);
			String p = "";
			for (Map.Entry<String, String> e : param.entrySet()) {
				if (e.getKey().equals("ts")) {
					p += e.getKey() + "=" + time + "&";
				} else if (e.getKey().equals("word")) {
					p += e.getKey() + "=" + keyword + "&";
				} else {
					p += e.getKey() + "=" + e.getValue() + "&";
				}
			}
			p = p.substring(0, p.length() - 1);
			String url2 = "http://www.baidu.com" + action + "?" + p;
			String str2 = CustomerHttpClient.get(url2);
			if (null == str2) {
				//log(handler, "关键词:\" " + key + " \"搜索失败!");
				log(handler,"搜索失败");
				continue;
			}
			Document doc2 = Jsoup.parseBodyFragment(str2);
			// 推广链接
			Elements hrefT = doc2.getElementsByClass("ec_resitem");
			//log(handler, "获取到推广链接:" + hrefT.size() + "条");
			for (Element element : hrefT) {
				if (element.select("a.ec_title").first() == null) {
					//Log.i("ConfigUtil", "被忽略:" + element.text());
					continue;
				}
				String h = element.select("a.ec_title").first().attr("href");
				String u = element.select("span.ec_site").first().text();
				for (String url__ : urls) {
					if (u.indexOf(url__) != -1 || url__.indexOf(u) != -1) {
						log(handler, u + "匹配成功!");
						// hrefs.put(h, u);
						clickHref(handler, u, h);
						break;
					}
				}
			}

//			// 普通链接
//			Elements hrefP = doc2.getElementsByClass("resitem");
//			log(handler, "获取到普通链接:" + hrefP.size() + "条");
//			for (Element element : hrefP) {
//				if (element.select("a.result_title").first() == null) {
//					Log.i("ConfigUtil", "被忽略:" + element.text());
//					continue;
//				}
//				String h = element.select("a.result_title").first().attr("href");
//				String u = element.select("span.site").first().text();
//				for (String url__ : urls) {
//					if (u.indexOf(url__) != -1 || url__.indexOf(u) != -1) {
//						log(handler, u + "成功匹配!");
//						// hrefs.put(h, u);
//						clickHref(handler, u, h);
//						break;
//					}
//				}
//			}

			// log(handler, "总共获取到匹配的结果:" + hrefs.size() + "条.");
		}

		// for (Map.Entry<String, String> m : hrefs.entrySet()) {
		// // 暂停半秒
		// try {
		// log(handler, "暂停1秒...");
		// Thread.sleep(1000);
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }
		// log(handler, "模拟点击:" + m.getValue());
		// String s = CustomerHttpClient.get(m.getKey());
		// if (null != s) {
		// log(handler, "点击:" + m.getValue() + "成功!!!");
		// } else {
		// log(handler, "点击:" + m.getValue() + "失败!!!");
		// }
		// Log.i("Str===" + m.getValue(), String.valueOf(s.length()));
		// }
		log(handler, "执行完毕!");
	}

	private void clickHref(Handler handler, String hrefname, String href) {
		try {
			//log(handler, "暂停1秒...");
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//log(handler, "模拟点击:" + hrefname);
		String s = CustomerHttpClient.get(href);
		if (null != s) {
			//log(handler, "点击:" + hrefname + "成功!!!");
			log(handler,"执行成功!");
		} else {
			//log(handler, "点击:" + hrefname + "失败!!!", true);
			log(handler,"执行失败!");
		}
	}

	private void log(Handler handler, String message, boolean... isError) {

		Message msg = new Message();
		if (isError.length > 0 && isError[0]) {
			msg.what = 1;
		} else {
			msg.what = 0;
		}
		msg.obj = Thread.currentThread().getName() + ">>>" + message + "\n\n";
		handler.sendMessage(msg);

	}

}
